package com.smartcar

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController

private const val REQUEST_ENABLE_BT = 1
private const val SCAN_PERIOD: Long = 50000
private const val TAG: String = "BluetoothScanFragment"

class BluetoothScanFragment : Fragment() {
    private var mScanning: Boolean = false
    private lateinit var buttonScan: Button
    private lateinit var bluetoothLeScanner: BluetoothLeScanner
    private lateinit var bluetoothAdapter: BluetoothAdapter
    private lateinit var mScanSettings: ScanSettings
    private val BluetoothAdapter.isDisabled: Boolean
        get() = !isEnabled

    private val handler: Handler = Handler()

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_bluetooth_scan, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val bluetoothManager = requireContext().getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
        bluetoothAdapter?.takeIf { it.isDisabled }?.apply {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
        }

        //创建ScanSettings的build对象用于设置参数
        //创建ScanSettings的build对象用于设置参数
        val builder =
            ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
        //android 6.0添加设置回调类型、匹配模式等
        //android 6.0添加设置回调类型、匹配模式等
        if (Build.VERSION.SDK_INT >= 23) { //定义回调类型
            builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
            //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
            builder.setMatchMode(ScanSettings.MATCH_MODE_STICKY)
        }
        //芯片组支持批处理芯片上的扫描
        //芯片组支持批处理芯片上的扫描
        if (bluetoothAdapter.isOffloadedScanBatchingSupported()) { //设置蓝牙LE扫描的报告延迟的时间（以毫秒为单位）
//设置为0以立即通知结果
            builder.setReportDelay(0L)
        }
        mScanSettings = builder.build()
        buttonScan = view.findViewById<Button>(R.id.button_scan_bluetooth)
        //findNavController().navigate(R.id.action_bluetoothScanFragment_to_operationPanelFragment)
        buttonScan.setOnClickListener {
            scanLeDevice()
            //findNavController().navigate(R.id.action_bluetoothScanFragment_to_bluetoothControlFragment)
        }
    }

    private fun scanLeDevice() {
        mScanning = true
        bluetoothLeScanner = bluetoothAdapter?.getBluetoothLeScanner()
        bluetoothLeScanner.startScan(null, mScanSettings, scanCallback)
        buttonScan.setText("正在扫描")
        // Stops scanning after a pre-defined scan period.
        handler.postDelayed({
            if(mScanning){
                mScanning = false
                stopScan()
            }
        }, SCAN_PERIOD)
    }
    private fun stopScan(){
        bluetoothLeScanner.stopScan(scanCallback);
    }
    private val scanCallback: ScanCallback = object : ScanCallback() {
        override fun onScanResult(
            callbackType: Int,
            result: ScanResult
        ) { //byte[] scanData=result.getScanRecord().getBytes();
//把byte数组转成16进制字符串，方便查看
//            Log.e("TAG","onScanResult :"+CYUtils.Bytes2HexString(scanData));
//            Log.e("TAG","onScanResult :"+result.getScanRecord().toString());
            if (result == null || result.device == null || TextUtils.isEmpty(result.device.name)) {
//                if (mUiHandler != null) {
//                    val message: Message = mUiHandler.obtainMessage()
//                    message.what = 1
//                    message.obj = "没有搜索到蓝牙设备"
//                    mUiHandler.sendMessage(message)
//                }
                //                return;
            }

            //00:15:85:14:9c:09
            val device = result.device
            val addr = device.address
            if(device.name == "MLT-BT05"){
                stopScan()
                buttonScan.setText(device.name + "_已连接_" +device.address)
                val bundle = Bundle()
                bundle.putString("address", device.address)
                findNavController().navigate(R.id.action_bluetoothScanFragment_to_operationPanelFragment,bundle)
            }
        }

        override fun onBatchScanResults(results: List<ScanResult>) {
            super.onBatchScanResults(results)
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
        }
    }

}
